package com.nian.global.utils;


import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 */
public class FileUtils {
    /**
     * @param request
     * @param path_deposit 新增目录名 支持多级不存在目录
     * @param file         待文件
     * @param isRandomName 是否要基于图片名称重新编排名称
     * @return
     */
    public static String uploadImage(HttpServletRequest request, String path_deposit, MultipartFile file, boolean isRandomName) {
        //上传
        try {
            String[] typeImg = {"gif", "png", "jpg"};

            if (file != null) {
                String origName = file.getOriginalFilename();// 文件原名称
                System.out.println("上传的文件原名称:" + origName);
                // 判断文件类型
                String type = origName.indexOf(".") != -1 ? origName.substring(origName.lastIndexOf(".") + 1, origName.length()) : null;
                if (type != null) {
                    boolean booIsType = false;
                    for (int i = 0; i < typeImg.length; i++) {
                        if (typeImg[i].equals(type.toLowerCase())) {
                            booIsType = true;
                        }
                    }
                    //类型正确
                    if (booIsType) {
                        //存放图片文件的路径
                        File paths = new File(ResourceUtils.getURL("classpath:").getPath());
                        System.out.println(paths.getPath());//如果你的图片存储路径在static下，可以参考下面的写法
                        File path = new File(paths.getAbsolutePath(), "static/");//开发测试模式中 获取到的是/target/classes/static/images/upload/
                        //String path=request.getSession().getServletContext().getRealPath("imgupload/");
                        System.out.print("文件上传的路径:" + path);

                        //组合名称
                        String fileSrc = path + path_deposit;
                        //是否随机名称
                        if (isRandomName) {
                            //随机名规则：文件名+_CY+当前日期+8位随机数+文件后缀名
                            origName = origName.substring(0, origName.lastIndexOf(".")) + "_CY" + formateString(new Date()) +
                                    MathUtils.getRandom620(8) + origName.substring(origName.lastIndexOf("."));
                        }
                        System.out.println("随机文件名：" + origName);
                        //判断是否存在目录
                        File targetFile = new File(fileSrc, origName);
                        if (!targetFile.exists()) {
                            targetFile.getParentFile().mkdirs();//创建目录
                        }

                        //上传
                        file.transferTo(targetFile);
                        //完整路径
                        System.out.println("完整路径:" + targetFile.getAbsolutePath());
                        String src = path_deposit + origName;
                        return src;
                    }
                }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 格式化日期并去掉”-“
     *
     * @param date
     * @return
     */
    public static String formateString(Date date) {
        SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
        String list[] = dateFormater.format(date).split("-");
        String result = "";
        for (int i = 0; i < list.length; i++) {
            result += list[i];
        }
        return result;
    }

    /**
     * 格式化日期并去掉”-“
     *
     * @param file
     * @return
     */
    public static String recogniseFileCharset(File file) throws Exception {

        String charsetName = "GBK";

        byte[] head = new byte[3];
        InputStream inputStream = new FileInputStream(file);
        inputStream.read(head);

        if (head[0] == -1 && head[1] == -2) {
            charsetName = "UTF-16";
        } else if (head[0] == -2 && head[1] == -1) {
            charsetName = "Unicode";
        } else if (head[0] == -17 && head[1] == -69 && head[2] == -65) {
            charsetName = "UTF-8";
        } else {
            byte[] text = new byte[(int) file.length()];
            System.arraycopy(head, 0, text, 0, 3);
            inputStream.read(text, 3, text.length - 3);
            for (int i = 0; i < text.length; i++) {
                int a = text[i] & 0xFF;
                int b = text[i + 1] & 0xFF;
                if (a > 0x7F) {//排除开头的英文或者数字字符
                    if (0xE3 < a & a < 0xE9 && b > 0x7F && b < 0xC0) {//符合utf8
                        charsetName = "UTF-8";
                    }
                    break;
                }
            }
        }

        inputStream.close();

        return charsetName;
    }

    /**
     * 创建文件
     *
     * @param  title
     * @param  content
     * @param  oPath
     * @return
     */
    public static void createFiles(String title, String content, String oPath) throws Exception {

        File directory = new File(oPath);
        if (!directory.exists()) { //判断目录是否存在
            directory.mkdirs();
        }

        File file = new File(oPath, title);
        if (file.exists()) { //判断文件是否存在
            file.delete();
        } else {
            file.createNewFile();
        }

        OutputStreamWriter fileWriter = new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8");
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(content);
        bufferedWriter.newLine();
        bufferedWriter.close();
        fileWriter.close();
    }

    /**
     * 创建文件
     *
     * @param  title
     * @param  content
     * @param  oPath
     * @return
     */
    public static void createFiles(String title, String content, String oPath, boolean newFlag) throws Exception {

        File file = new File(oPath + title);

        if (newFlag && file.exists()) {
            file.delete();
        }

        OutputStreamWriter fileWriter = new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8");
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(content);
        bufferedWriter.newLine();
        bufferedWriter.close();
        fileWriter.close();
    }

    /**
     * 创建文件
     *
     * @return
     */
    public static String copyFile(String fileName, String oPath) throws Exception {

        URL url = Thread.currentThread().getContextClassLoader().getResource("template/");
        File directory = new File(url.toURI());
        if (!directory.isDirectory()) {
            throw new Exception("template不是目录！");
        }
        File[] files = directory.listFiles();
        if (files == null || files.length <= 0) {
            throw new Exception("目录template下没有文件！");
        }
        String iFilePath = "";
        String oFilePath = "";
        for (File file : files) {
            if (!fileName.equals(file.getName())) {
                continue;
            }
            iFilePath = file.getAbsolutePath();
            oFilePath = oPath + fileName.substring(0,fileName.indexOf(".")) + "_" + BaseUtils.currentTime("yyyyMMdd HHmmss") + fileName.substring(fileName.indexOf("."));
        }
        if (StringUtils.isEmpty(iFilePath)) {
            throw new Exception("目录template下没有指定模板！");
        }
        // 源文件路径
        Path sourcePath = Paths.get(iFilePath);
        // 目标文件路径及新名称
        Path targetPath = Paths.get(oFilePath);
        // 复制文件，并设置为替换现有文件
        Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);

        System.out.println("文件[" + fileName + "]复制并重命名[" + oFilePath + "]成功！");
        return oFilePath;
    }
}
